//
//  WCBShaixuViewController.m
//  WeChatBuniess
//
//  Created by Guo Rui on 2017/12/15.
//  Copyright © 2017年 GR Harry. All rights reserved.
//

#import "WCBShaixuViewController.h"
#import "WCBDataHelper.h"
#import "NSDate+TFCore.h"
#import "WCBShaixuCell.h"
#import "TFToast.h"
#import "WCASessionManager.h"
#import "TFWeakTimer.h"
#import "UIImage+Ex.h"

@interface WCBShaixuViewController ()

@property (strong, nonatomic) NSMutableArray *dataArray;
@property (strong, nonatomic) TFWeakTimer *timer;
@property (strong, nonatomic) UIButton *confirmButton;
@end

@implementation WCBShaixuViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"筛选内容";
    self.view.backgroundColor = [UIColor colorWithRed:0.94 green:0.94 blue:0.95 alpha:1.00];
    
    self.dataArray = [NSMutableArray arrayWithCapacity:0];
    
    for (NSString *date in [WCBDataHelper.sharedHelper getAllYears]) {
        WCBShaixuModel *model = [[WCBShaixuModel alloc] init];
        model.startDesc = date;
        model.startDate = [self startIntervalWithYear:date];
        model.endDate = [self lastIntervalWithYear:date];
        model.custom = NO;
        [self.dataArray addObject:model];
    }
    
    // 自定义模型
    NSArray *allMonths = [WCBDataHelper.sharedHelper getAllMonths];
    WCBShaixuModel *customModel = [[WCBShaixuModel alloc] init];
    customModel.startDesc = allMonths.firstObject;
    customModel.endDesc = allMonths.lastObject;
    customModel.startDate = [self startIntervalWithMonth:customModel.startDesc];
    customModel.endDate = [self lastIntervalWithMonth:customModel.endDesc];
    customModel.custom = YES;
    [self.dataArray addObject:customModel];
    [self.tableView reloadData];
    
    [self.tableView registerClass:[WCBShaixuCell class] forCellReuseIdentifier:@"ID"];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.tableFooterView = [[UIView alloc] init];
    self.tableView.contentInset = UIEdgeInsetsMake(20, 0, 0, 0);
}

#pragma mark - Private
- (NSTimeInterval)startIntervalWithYear:(NSString *)year
{
    NSDate *firstDayDate = [NSDate tf_dateWithDateString:[NSString stringWithFormat:@"%@-01-01", year] format:@"YYYY-MM-dd"];
    return [firstDayDate timeIntervalSince1970];
}

- (NSTimeInterval)lastIntervalWithYear:(NSString *)year
{
    NSDate *firstDayDate = [NSDate tf_dateWithDateString:[NSString stringWithFormat:@"%@-01-01", year] format:@"YYYY-MM-dd"];
    NSDate *lastDayDate = firstDayDate.tf_endDateOfYear;
    return [lastDayDate timeIntervalSince1970];
}

- (NSTimeInterval)lastIntervalWithMonth:(NSString *)month
{
    NSDate *firstDayDate = [NSDate tf_dateWithDateString:[NSString stringWithFormat:@"%@-01", month] format:@"YYYY-MM-dd"];
    NSDate *lastDayDate = firstDayDate.tf_endDateOfMonth;
    return [lastDayDate timeIntervalSince1970];
}

- (NSTimeInterval)startIntervalWithMonth:(NSString *)month
{
    NSDate *firstDayDate = [NSDate tf_dateWithDateString:[NSString stringWithFormat:@"%@-01", month] format:@"YYYY-MM-dd"];
    NSDate *lastDayDate = firstDayDate.tf_startDateOfMonth;
    return [lastDayDate timeIntervalSince1970];
}

#pragma mark - Actions
- (void)confirmDidClick:(UIButton *)button
{
    // 查找选中
    WCBShaixuModel *selectModel = nil;
    for (WCBShaixuModel *model in self.dataArray) {
        if (model.selected) {
            selectModel = model;
            break;
        }
    }
    
    // 检测数据正确性
    if (selectModel == nil) {
        [TFToast toast:@"请选择成书内容的时间段"];
        return;
    }
    
    if (selectModel.endDate < selectModel.startDate) {
        [TFToast toast:@"结束时间不应该早于开始时间"];
        return;
    }
    
    __weak WCBShaixuViewController *_self = self;
    self.confirmButton.enabled = NO;
    
    NSDictionary *param = @{ @"bookId" : self.bookId, @"startDate" : @(selectModel.startDate * 1000), @"endDate" : @(selectModel.endDate * 1000) };
    [WCASessionManager POST:@"weimport/mtime/selectWeChatData" parameters:param success:^(NSURLSessionDataTask *task, id responseObject) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            NSString *code = [responseObject objectForKey:@"code"];
            if ([code isEqualToString:@"000"]) {
                [_self pollingForBookCreateSuccess];
//                [TFToast toast:@"保存成功!"];
//                [_self.navigationController popViewControllerAnimated:YES];
//                if (_self.completion) {
//                    _self.completion(selectModel.startDate, selectModel.endDate);
//                }
            }
            else {
                [TFToast toast:[NSString stringWithFormat:@"请求失败 %@", code]];
            }
        });
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [TFToast toast:@"您的网络不给力，请检查网络后重试！"];
        });
    }];
}

- (void)pollingForBookCreateSuccess
{
    self.timer = [TFWeakTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(requestForQueryBookCreateSuccess) userInfo:nil repeats:YES dispatchQueue:dispatch_get_main_queue()];
}

- (void)requestForQueryBookCreateSuccess
{
    __weak WCBShaixuViewController * weakself = self;
    WCAHTTPRequestSerializer *serializer = [WCAHTTPRequestSerializer serializer];
    [WCASessionManager setRequestSerialization:serializer];
    
    NSString *userId = WCBDataHelper.sharedHelper.getCurrentUserModel.userId;
    [WCASessionManager POST:@"weimport/mtime/getWeChatBookInfo" parameters:@{ @"bookId": self.bookId, @"userId": userId } success:^(NSURLSessionDataTask *task, id responseObject) {
        
        NSDictionary *result = [responseObject objectForKey:@"bookObj"] ? [responseObject objectForKey:@"bookObj"] : @{ @"created" : @(NO) };
        if ([[result objectForKey:@"created"] boolValue] && [[result objectForKey:@"pageSize"] integerValue]) {
            // 书已做完
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [weakself.timer invalidate];
                weakself.timer = nil;
                [TFToast toast:@"保存成功"];
                weakself.confirmButton.enabled = YES;
                WCBWeChatBookModel *bookModel = [WCBWeChatBookModel modelWithDict:result];
                [weakself.navigationController popViewControllerAnimated:YES];
                if (weakself.completion) {
                    weakself.completion(bookModel);
                }
            });
        }
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"获取书接口错误 - %@", error.localizedDescription);
        dispatch_async(dispatch_get_main_queue(), ^{
            weakself.confirmButton.enabled = YES;
        });
    }];
}


#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    WCBShaixuCell *cell = (WCBShaixuCell *)[tableView dequeueReusableCellWithIdentifier:@"ID" forIndexPath:indexPath];
    
    WCBShaixuModel *model = [self.dataArray objectAtIndex:indexPath.row];
    cell.model = model;
    
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = [UIColor whiteColor];
    view.frame = CGRectMake(0, 0, self.view.frame.size.width, 70.f);
    
    UILabel *label = [[UILabel alloc] init];
    label.textColor = [UIColor blackColor];
    label.font = [UIFont systemFontOfSize:23];
    label.text = @"请选择需要成书内容的时间段:";
    label.frame = CGRectMake(25.f, 0, view.frame.size.width, view.frame.size.height);
    [view addSubview:label];
    
    return view;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = [UIColor clearColor];
    view.frame = CGRectMake(0, 0, self.view.frame.size.width, 70.f + 30.f);
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake((CGRectGetWidth(self.view.frame) - 400) / 2, 10 + 30.f, 400, 60);
    button.layer.cornerRadius = 5.f;
    button.layer.masksToBounds = YES;
    [button setTitle:@"确认" forState:UIControlStateNormal];
    [button setTitle:@"正在保存..." forState:UIControlStateDisabled];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    [button setBackgroundImage:[UIImage tf_imageWithColor:[UIColor colorWithRed:0.11 green:0.62 blue:0.94 alpha:1.00]] forState:UIControlStateNormal];
    [button setBackgroundImage:[UIImage tf_imageWithColor:[UIColor lightGrayColor]] forState:UIControlStateDisabled];
    
    button.titleLabel.font = [UIFont systemFontOfSize:25];
    [button addTarget:self action:@selector(confirmDidClick:) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:button];
    
    self.confirmButton = button;
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    WCBShaixuModel *model = [self.dataArray objectAtIndex:indexPath.row];
    CGFloat h = 50.f;
    h += (model.custom ? 50 : 0);
    return h;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 70.f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 100.f;
}

- (void)dealloc {
    NSLog(@"\n************\n %@ dealloc \n************", self.class);
}
@end

@implementation WCBShaixuModel
@end

